package bch.rocketmq.service;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@RequiredArgsConstructor
public class CompanyScannerService {

    private final JdbcTemplate jdbcTemplate;

    public void scanCompaniesMultiThread(int threadCount) {
        try (ExecutorService executor = Executors.newFixedThreadPool(threadCount)) {
            for (int shard = 0; shard < threadCount; shard++) {
                int finalShard = shard;
                executor.submit(() -> scanShard(finalShard, threadCount));
            }
        }
    }

    @Data
    private static class Company {
        private final Long id;
        private final String name;
        private final Long parentId;

        public Company(Long id, String name, Long parentId) {
            this.id = id;
            this.name = name;
            this.parentId = parentId;
        }
    }

    private void scanShard(int shard, int totalShards) {
        System.out.printf("线程 %s 扫描分片 %d/%d%n",
                Thread.currentThread().getName(), shard, totalShards);

        String sql = "SELECT id, name, parent_id FROM company WHERE MOD(id, ?) = ?";

        List<Company> companies = jdbcTemplate.query(
                sql,
                new Object[]{totalShards, shard},
                (rs, rowNum) -> new Company(
                        rs.getLong("id"),
                        rs.getString("name"),
                        rs.getObject("parent_id") != null ? rs.getLong("parent_id") : null
                )
        );

        for (Company company : companies) {
            // 处理逻辑
            System.out.println("线程 " + Thread.currentThread().getName() + " 处理公司: " + company);
        }
    }
}
